package com.qfedu.controller;

import com.qfedu.dao.PetsDao;
import com.qfedu.dto.PetsAndUser;
import com.qfedu.entity.Pets;
import com.qfedu.entity.User;
import com.qfedu.service.intf.PetsService;
import com.qfedu.service.intf.UserService;
import com.qfedu.vo.PageVo;
import com.qfedu.vo.R;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api/pets/")
public class PetsController {
    @Resource
    PetsService service;

    @GetMapping("add.do")
    public R add(Pets pets) {
        return service.add(pets);
    }

    @PostMapping("del.do")
    public R del(int id) {
        return service.del(id);
    }

    @GetMapping("update.do")
    public R update(Pets pets) {
        return service.update(pets);
    }

    @GetMapping("all.do")
    public PageVo all(int page, int limit, PetsAndUser petsAndUser) {
        PageVo pageVo = service.queryPage(page, limit,petsAndUser);
        System.out.println(pageVo);
        return pageVo;
    }

    /**
     * 文件上传
     * 有没有可能上传的文件名都一样？会出现什么问题？怎么解决？
     */
    @RequestMapping("fileupload.do")
    public R fileUp(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.验证上传的文件是否为空
        if (file.isEmpty()) {
            return R.fail();
        } else {
            //文件有内容
            //2.获取文件名称
            String fn = file.getOriginalFilename();
            //3.获取上传的文件内容
            byte[] data = file.getBytes();
            //4.存储上传的内容到服务器上 输出流
            //存储到发布路径  真实路径
            File f = new File(request.getServletContext().getRealPath("/"), fn);

            FileOutputStream fos = new FileOutputStream(f);
            fos.write(data);
            fos.close();

            System.out.println("http://localhost:8080/" + fn);
            return R.ok("http://localhost:8080/" + fn);
        }
    }

    @GetMapping("download.do")
    public void download(HttpServletResponse response) throws IOException {
        service.exportData(response);
    }


}
